/**
 * @(#) DExpenseMediator.as
 *
 * @date		2010. 12. 23.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	석식비 - Mediator
 *
 */
package com.skt.common_hr.holotreq.view
{
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.approval.RequestApprovalMediator;
	import com.skt.common_hr.common.calendar.Holiday;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.puremvc.OverViewMediator;
	import com.skt.common_hr.holotreq.HolOtReqFacade;
	import com.skt.common_hr.holotreq.event.WorkTimeEvent;
	import com.skt.common_hr.holotreq.model.DExpenseListProxy;
	import com.skt.common_hr.holotreq.model.HolOtReqProxy;
	import com.skt.common_hr.holotreq.model.cProxy;
	import com.skt.common_hr.holotreq.model.vo.DateVO;
	import com.skt.common_hr.holotreq.view.calendar.DExpCalendar;
	import com.skt.common_hr.holotreq.view.components.HolOtReqView;
	import com.skt.common_hr.holotreq.view.components.ReqHolOtReq;
	import com.skt.common_hr.holotreq.model.TeamVacationProxy;
	import com.skt.common_hr.holotreq.model.VacationQuotaProxy;
	import com.skt.common_hr.holotreq.model.vo.TeamVacationVO;
	import com.skt.common_hr.holotreq.model.vo.VacationVO;
	import com.wcl.utils.DateUtil;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.core.IFlexDisplayObject;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;


	public class HolOtReqMediator extends OverViewMediator
	{
		public static const NAME:String = "HolOtReqMediator";

		private var bExecDialog:Boolean = false;
		private var begda:Date = new Date();
		private var endda:Date = new Date();

		/**
		* 생성자
		*
		* @param
		* @return void
		*/
        public function HolOtReqMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
        }

		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		override protected function initializeView():void
 		{
			super.initializeView();
			preloadData();
			setEventListener();
 		}

 		/**
		 * 휴가일수 안내를 로드한다.
		 * 
		 * @param
		 * @return void
		 */
		private function preloadData():void
 		{
			// 휴가일수 안내를 로드한다.
			loadVacationQuota();
 		}
 		
 		private function setEventListener():void
 		{
			view.addEventListener(HolOtReqView.CLICK_REQUEST, onClickRequest);
			view.addEventListener(HolOtReqView.CLICK_QUERY, onClickQuery);
			view.addEventListener(HolOtReqView.DELETE_REQUEST, onDeleteRequest);
			view.addEventListener(HolOtReqView.MODIFY_REQUEST, onModifyRequest);
			view.addEventListener(HolOtReqView.VIEW_REQUEST, onViewRequest);
			view.addEventListener(WorkTimeEvent.CHANGED_MONTH, onChangedMonth);		// Calendar에서 월이 변경되어 있을때
			
			view.calendar.addEventListener(DExpCalendar.CLICK_REQUEST, onClickRequest);
 		}


		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		override protected function activatedView():void
 		{
 			setEventListener(); 			
 			view.currentCalendarDate = DateUtil.todayNoTime();
 			 			
 			
 		}

  		private function loadList():void
  		{
 			var proxy:DExpenseListProxy = facade.retrieveProxy(DExpenseListProxy.NAME) as DExpenseListProxy;
 			proxy.load(Variables.myPernr, view.begda );
  		}

  		private function loadList2(sDate:Date):void
  		{
 			var proxy:DExpenseListProxy = facade.retrieveProxy(DExpenseListProxy.NAME) as DExpenseListProxy;
 			proxy.load(Variables.myPernr, sDate);
  		}
  		
  		private function onChangedMonth(event:WorkTimeEvent):void
 		{
  			var targetMonth:String = DateUtil.toYYYYMMString(event.start);//event.beginDate.fullYear.toString() + ((event.beginDate.month+1<10)?"0":"") + (event.beginDate.month+1).toString();
  			loadList2(event.start);
 			loadCalendarData(targetMonth);
 			loadTeamVacation(targetMonth);

 			//loadOverTime(targetMonth);  
 			//view.selectedDate = event.beginDate; 
 		}

  		private function loadCalendarData(month:String):void
 		{
 			var dateProxy:cProxy = facade.retrieveProxy(cProxy.NAME) as cProxy;
 			dateProxy.load(Variables.myPernr, month);
 		}

		private function loadTeamVacation(month:String):void
 		{
  			var teamVacationProxy:TeamVacationProxy = facade.retrieveProxy(TeamVacationProxy.NAME) as TeamVacationProxy;
 			teamVacationProxy.load(Variables.myPernr, month);
		}

 		private function loadVacationQuota():void
 		{
 			var quotaProxy:VacationQuotaProxy = facade.retrieveProxy(VacationQuotaProxy.NAME) as VacationQuotaProxy;
 			quotaProxy.load(Variables.myPernr, DateUtil.thisYear().toString());
 		}
 		 		 		
  		private function onClickQuery(e:Event):void
  		{
  			loadList();
  		}


 		private function onClickRequest(e:Event):void
  		{
  			execReqExpense();
  			facade.sendNotification(ReqHolOtReqMediator.EXEC_NEW_REQUEST);
  		}

 		private function onViewRequest(e:Event):void
  		{
  			var key:String = view.selected_vo.GWAREKEY;
  			execReqExpense();
  			//Alert.show("key = " + key);
  			facade.sendNotification(ReqHolOtReqMediator.EXEC_READ_REQUEST, key);
    	}


  		private var reqDExpense:IFlexDisplayObject = null;
  		private function execReqExpense():void
  		{
  			var reqMediator:ReqHolOtReqMediator;

  			if(reqDExpense==null) {	// 신규 생성
  				reqDExpense = PopUpManager.createPopUp(view, ReqHolOtReq, true);
  				ReqHolOtReq(reqDExpense).selectedDate = view.calendar.selectedDate;
  				PopUpManager.centerPopUp(reqDExpense);

				reqMediator = new ReqHolOtReqMediator(reqDExpense);
				facade.registerMediator(reqMediator);
  			}
  			else {
  				PopUpManager.addPopUp(reqDExpense, view, true);
  				ReqHolOtReq(reqDExpense).selectedDate = view.calendar.selectedDate;
  				reqMediator = facade.retrieveMediator(ReqHolOtReqMediator.NAME) as ReqHolOtReqMediator;
  			}
  			bExecDialog = true;
  		}

		private function onModifyRequest(e:Event):void
  		{
  			var key:String = view.selected_vo.GWAREKEY;
  			execReqExpense();
  			facade.sendNotification(ReqHolOtReqMediator.EXEC_MODI_REQUEST, key);
  		}

 		private function onDeleteRequest(e:Event):void
  		{
  			var message:String;
  			if(view.selected_vo.WSTATUS == "2") {
  				message = DateUtil.toDefaultString(view.selected_vo.BEGDA) + " 일자 석식비 신청을 취소하시겠습니까? ";
	  			CommonAlert.showMsgYesNo("", message, null, "확인", view, onOKDelete, onCancelDelete);
  			}
  			else if(view.selected_vo.WSTATUS == "4") {
  				message = "반려된 석식비 신청을 삭제하시겠습니까? ";
	  			CommonAlert.showMsgYesNo("", message, null, "확인", view, onOKDelete, onCancelDelete);
  			}
  		}

  		private function onOKDelete():void
  		{
  			var proxy:HolOtReqProxy = facade.retrieveProxy(HolOtReqProxy.NAME) as HolOtReqProxy;
  			proxy.del(view.selected_vo.GWAREKEY);
  		}

  		private function onCancelDelete():void
  		{

  		}

		// 본인 기록은 제외
		private function getTeamList(proxy:TeamVacationProxy):ArrayCollection
		{
			var arr:ArrayCollection = new ArrayCollection();
			for each(var vo:TeamVacationVO in proxy.teamVacationList) {
				if(vo.PERNR!=Variables.myPernr) {
					arr.addItem(vo);
				}
			}
			return arr;
		}

		private function setOTList(proxy:cProxy):void
		{
			var otList:ArrayCollection = new ArrayCollection();
			var OT011:Object = new Object();	OT011.gubun = "평일";		OT011.time = 0;
			var OT012:Object = new Object();	OT012.gubun = "평일야간";	OT012.time = 0;
			var OT021:Object = new Object();	OT021.gubun = "휴일";		OT021.time = 0;
			var OT022:Object = new Object();	OT022.gubun = "휴일야간";	OT022.time = 0;
			
			for each(var vo:VacationVO in proxy.vacationList) {
				if(vo.WSTATUS == "2" || vo.WSTATUS == "3") {
					if(vo.AWART == "2010") {
						OT011.time += vo.OT011;
						OT012.time += vo.OT012;
						OT021.time += vo.OT021;
						OT022.time += vo.OT022;
					}
				}
			}
			otList.addItem(OT011);
			otList.addItem(OT012);
			otList.addItem(OT021);
			otList.addItem(OT022);
			view.otList = otList;
		}
		  		
		private function setCalendar(proxy:cProxy):void
		{
			view.bHoliVacation  = proxy.bHoliVacation;
			view.holidayList 	= toCalendarHoliday(proxy.holidayList);
			//view.vacationList 	= toCalendarItems(proxy.vacationList);
			//bMorningOT = proxy.bMorningOT;
		}  		
 		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		*
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array
		{
			return basicInterestMessages.concat( [
					DExpenseListProxy.LOAD_DINNER_LIST_COMPLETE,
					DExpenseListProxy.LOAD_DINNER_LIST_FAILED,
					HolOtReqProxy.DEL_DINNER_COMPLETE,
					HolOtReqProxy.DEL_DINNER_FAILED,
					ReqHolOtReqMediator.CLOSED_REQUEST_VIEW,
					RequestApprovalMediator.APPROVAL_COMPLETE,
					HolOtReqFacade.LOAD_CALENDAR_COMPLETE,
					HolOtReqFacade.LOAD_VACATION_QUOTA_COMPLETE,
					HolOtReqFacade.LOAD_TEAMVACATION_COMPLETE
					
					]);
		}


		/**
		* Noti별로 처리한다.
		*
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			super.handleNotification(note);
			switch(note.getName())
			{
				case HolOtReqFacade.LOAD_TEAMVACATION_COMPLETE:
					//view.teamVacationList = (note.getBody() as TeamVacationProxy).teamVacationList;
					view.teamVacationList = getTeamList((note.getBody() as TeamVacationProxy));
					break;
				case HolOtReqFacade.LOAD_VACATION_QUOTA_COMPLETE:
					trace("loaded quota");
					view.quotaList = (note.getBody() as VacationQuotaProxy).quotaList;
					//Alert.show("load quota : " + view.quotaList.length);
					break;

				
				case HolOtReqFacade.LOAD_CALENDAR_COMPLETE:
					setCalendar(note.getBody() as cProxy);
					setOTList(note.getBody() as cProxy);
					//setStatusMessage("근무/휴가 데이터가  로드되었습니다.");
					break;				
				case DExpenseListProxy.LOAD_DINNER_LIST_COMPLETE:
					//view.dataProvider = (note.getBody() as DExpenseListProxy).otList;
					view.calendar.otReq = (note.getBody() as DExpenseListProxy).otList; 					
					//view.total_days = (note.getBody() as DExpenseListProxy).daysOfConfirm;
					//Alert.show("loaded: " + view.dataProvider.length);
					//commonFacade.setStatusMessage("STATUS_LOADED_LIST", [view.dataProvider.length]);
					break;
				case HolOtReqProxy.DEL_DINNER_COMPLETE:
					if(!bExecDialog) {
						loadList();
						CommonAlert.showMessage("", "삭제되었습니다.");
					}
					break;
				case RequestApprovalMediator.APPROVAL_COMPLETE:
					loadList();
					break;
				case ReqHolOtReqMediator.CLOSED_REQUEST_VIEW:
				 	var o:Object = note.getBody();
					loadList2(o.selectedDate);
					bExecDialog = false;
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}


		private function toCalendarHoliday(src:ArrayCollection):ArrayCollection
		{
			var coll:ArrayCollection = new ArrayCollection();
			for each(var rec:DateVO in src) {
				var vo:Holiday = new Holiday();
				vo.DATUM = new Date(rec.DATUM);
				vo.DTYPE = rec.DTYPE;
				vo.DTEXT = rec.DTEXT;
				coll.addItem(vo);
			}
			return coll;
		}






		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Event handler (from View, Internal or....)
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////


		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():HolOtReqView
        {
            return viewComponent as HolOtReqView;
        }
	}
}